package org.jeecg.modules.article.service.impl;

import org.jeecg.modules.article.constant.ArticleLikeConstant;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.article.mapper.ClickLikeMapper;
import org.jeecg.modules.article.service.ClickLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * TODO:  点赞功能
 *
 *
 * @author ZhangHaoyu
 */
@Service
public class ClickLikeServiceImpl  implements ClickLikeService {
    @Autowired
    ClickLikeMapper clickLikeMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean IsClickLike(String articleid, String userid) {




        return clickLikeMapper.IsClickLike(articleid,userid);
    }
//    @Override
//    public boolean IsClickLike(String articleid, String userid) {
//
//        return clickLikeMapper.IsClickLike(articleid,userid);
//    }

    @Override
    public int InsertClickLike(String articleid, String userid) {
        boolean success = false;
        /*
        操作redis
            先从redis中获取 USER_LIKE_ARTICLE_KEY 集合（不存在返回的集合size=0）

            更新 USER_LIKE_ARTICLE_KEY
         */
        synchronized (this){
            // 获取点赞本文章的用户id集合 ，不存在为null
            Set<String> ids = (Set<String>) redisUtil.hget(ArticleLikeConstant.USER_LIKE_ARTICLE_KEY, articleid);

            if (ids==null){
                ids = new LinkedHashSet<>();
            }
            success = ids.add(userid);
            // 更新 USER_LIKE_ARTICLE_KEY
            redisUtil.hset(ArticleLikeConstant.USER_LIKE_ARTICLE_KEY, articleid, ids);
        }


        return success?1:0;
    }
//    @Override
//    public int InsertClickLike(String articleid, String userid) {
//        int result=clickLikeMapper.InsertClickLike(articleid,userid);
//        return result;
//    }

    @Override
    public int DeleteClickLike(String articleid, String userid) {
        boolean success = false;
        synchronized (this){
            // 获取点赞本文章的用户id集合 ，不存在为null
            Set<String> ids = (Set<String>) redisUtil.hget(ArticleLikeConstant.USER_LIKE_ARTICLE_KEY, articleid);

            success = ids.remove(userid);

            // 更新 USER_LIKE_ARTICLE_KEY
            redisUtil.hset(ArticleLikeConstant.USER_LIKE_ARTICLE_KEY, articleid, ids);

        }
        return success?1:0;
    }
//    @Override
//    public int DeleteClickLike(String articleid, String userid) {
//        int result=clickLikeMapper.DeleteClickLike(articleid,userid);
//        return result;
//    }
}
